﻿using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using S_Userinfor.Domains;
using S_UserInfor.Infrasturctre.Interface;
using S_UserInfor.Read.Api.Application.Commands;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace S_UserInfor.Read.Api.Application.CommandsHanders
{
    /// <summary>
    /// 登录返回Token信息
    /// </summary>
    public class RegUserCommandHander:IRequestHandler<RegUserCommand, RegUserDataDTO>
    {
        private readonly IConfiguration _configuration;
        private readonly IUserRepository _userRepository;

        public RegUserCommandHander(IConfiguration configuration, IUserRepository userRepository)
        {
            _configuration = configuration;
            _userRepository = userRepository;
        }

        public async Task<RegUserDataDTO> Handle(RegUserCommand request, CancellationToken cancellationToken)
        {
            var list = await _userRepository.GetAsync(x => x.UName == request.UName && x.UPwd == request.UPwd);
            RegUserDataDTO regUserDataDTO = new RegUserDataDTO();
            foreach (var item in list)
            {
                var info = new RegUserDataDTO
                {
                    UName = request.UName,
                    UPwd = request.UPwd,
                    Token = JwtNewString(item.UName, item.Id),
                };
                return info;
            }
            if (list.Count != 0)
            {
                return regUserDataDTO;
            }
            else
            {
                return null;
            }
        }




        /// <summary>
        /// 生成Token令牌
        /// </summary>
        /// <param name="uid">用户唯一标识  主键</param>
        /// <returns></returns>
        private string JwtNewString(string name, int id)
        {
            //1.生成JWT
            //Header，选择标签名算法
            var signingAlogorithm = SecurityAlgorithms.HmacSha256;
            //Payload,存放用户信息 ， 下面我们就放一个id
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub,id.ToString()),
                new Claim(ClaimTypes.Role,name),
                new Claim(ClaimTypes.UserData,"测试")
            };

            //Signature
            //取出私钥并以utf8编码字节输入
            var secretByte = Encoding.UTF8.GetBytes(_configuration["Authentication:SecreKey"]);
            //使用非对称算法对私钥进行加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            //使用HmacSha256来验证加密后的私钥生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, signingAlogorithm);
            var Token = new JwtSecurityToken(
                    issuer: _configuration["Authentication:Issuer"],
                    audience: _configuration["Authentication:Audience"],
                    claims: claims,
                    notBefore: DateTime.UtcNow,
                    expires: DateTime.UtcNow.AddDays(1),
                    signingCredentials
                );

            //生成字符串token
            var TokenStr = new JwtSecurityTokenHandler().WriteToken(Token);
            return TokenStr;
        }
    }
}
